import router from '@/router'
import { createPinia, defineStore } from 'pinia'
import { globalStoreType } from './types'
import piniaPluginPersistedstate from 'pinia-plugin-persistedstate'
import piniaPersist from '@/config/piniaPersist'
import { codeLoginApi, getInfo, loginApi } from '@/api/modules/user'
import { ElMessage } from 'element-plus'

const pinia = createPinia()

export const GlobalStore = defineStore({
	id: 'GlobalStor',
	state: (): globalStoreType => ({
		storeSize: 'large',
		token: '',
		info: {},
	}),
	getters: {},
	actions: {
		async login(login) {
			const { data } = login.code2 ? await codeLoginApi(login) : await loginApi(login)
			this.token = data
			ElMessage.success('登入成功！')
			router.push('/welcome')
			this.getNickname()
		},
		// 退出登入
		async logOut() {
			this.eliminate()
		},
		async getNickname() {
			const { data } = await getInfo()
			this.info = data
		},
		eliminate() {
			this.token = ''
			this.info = {}
		},
	},
	persist: piniaPersist('GlobalStore'),
})

pinia.use(piniaPluginPersistedstate)

export default pinia
